package com.javaex.book.controller;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.javaex.book.annotation.Controller;
import com.javaex.book.annotation.RequestMapping;
import com.javaex.book.pojo.User;
import com.javaex.book.service.UserService;
import com.javaex.book.service.impl.UserServiceImpl;
import com.javaex.book.utils.BeanUtils;
import com.javaex.book.utils.Constants;
import com.javaex.book.utils.Pages;
import com.javaex.book.utils.Pagination;
import com.javaex.book.utils.RequestMethod;
import com.javaex.book.utils.ReturnResult;
import com.javaex.book.utils.TypeConvertUtils;
import com.javaex.book.utils.WebUtils;

/**
 * 用户相关请求处理
 *
 * @author 黄星琦
 * @Date 2022年1月17日
 */
@Controller()
public class UserController {
	
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	private UserService userService = new UserServiceImpl();
	private static final String KAPTCHA_SESSION_KEY = com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

	/**
	 * 前往登录页面
	 */
	@RequestMapping("/user/login")
	public String toLogin(HttpSession session) {
		return Pages.LOGIN_OR_REGISTER;
	}
	
	/**
	 * 登录
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/user/login")
	public String login(HttpServletRequest req, HttpSession session, HttpServletResponse resp) {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		logger.info("用户登录：username={}, password={}", username, password);
		
		ReturnResult result = userService.login(username, password);
		// 登录失败
		if (result.getCode() == Constants.Code.FAIL) {
			req.setAttribute("username", username);
			req.setAttribute("message", result.getMessage());
			return Pages.LOGIN_OR_REGISTER;
		}
		
		Cookie cookie = new Cookie("username", username);
		cookie.setMaxAge(60 * 60 * 24 * 7);	// Cookie有效期为7天
		cookie.setPath(req.getContextPath() + "/user/login");
		resp.addCookie(cookie);
		// 登录成功，把用户数据保存到session中。前往首页
		session.setAttribute("loginUser", result.getData());
		return Pages.redirect("/");
	}
	
	/**
	 * 前往注册页面
	 */
	@RequestMapping("/user/register")
	public String toRegister() {
		return Pages.LOGIN_OR_REGISTER;
	}
	
	/**
	 * 注册
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/user/register")
	public String register(HttpServletRequest req, HttpSession session) {
		User user = BeanUtils.injectDataIntoBean(User.class, (type, name) -> TypeConvertUtils.typeConvert(type, req.getParameter(name)));
		logger.info("用户注册: {}", user);
		String code = req.getParameter("code");
		
		// 比较验证码
		String token = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
		session.removeAttribute(KAPTCHA_SESSION_KEY);
		if (code == null || !code.equalsIgnoreCase(token)) {
			req.setAttribute("username", user.getUsername());
			req.setAttribute("email", user.getEmail());
			req.setAttribute("message", "验证码错误");
			return Pages.LOGIN_OR_REGISTER;
		}
		
		ReturnResult result = userService.register(user);
		if (result.getCode() == Constants.Code.FAIL) {
			req.setAttribute("message", result.getMessage());
			req.setAttribute("username", user.getUsername());
			req.setAttribute("email", user.getEmail());
			return Pages.LOGIN_OR_REGISTER;
		}
		session.setAttribute("loginUser", user);
		return Pages.redirect("/");
	}
	
	/**
	 * 退出登录
	 */
	@RequestMapping("/user/logout")
	public String logout(HttpSession session) {
		logger.info("退出登录: {}", session.getAttribute("loginUser"));
		session.removeAttribute("loginUser");
		return Pages.redirect("/");
	}
	
	/**
	 * 前往用户详情页
	 */
	@RequestMapping("/user/detail")
	public String userDetial(HttpServletRequest req, HttpSession session) {
		String userId = req.getParameter("id");
		User user = null;
		if (userId == null) {
			user = (User) session.getAttribute("loginUser");
		} else {
			user = userService.queryUserById(Integer.parseInt(userId));
		}
		session.setAttribute("oldUser", user);
		req.setAttribute("user", user);
		return Pages.USER_EDIT;
	}
	
	/**
	 * 修改用户信息
	 */
	@RequestMapping(value = "/user/detail", method = RequestMethod.POST)
	public String updateUser(HttpServletRequest req, HttpSession session) {
		User user = BeanUtils.injectDataIntoBean(User.class, (type, name) -> TypeConvertUtils.typeConvert(type, req.getParameter(name)));
		User oldUser = (User) session.getAttribute("oldUser");
		
		// 如果用户原来的信息与提交的信息相同，不修改
		if (user.equals(oldUser)) {
			req.setAttribute("user", user);
			return Pages.USER_EDIT;
		}
		
		logger.info("修改用户信息：{}", user);
		Integer rows = userService.updateUser(user);
		if (rows == 0) {
			req.setAttribute("message", "修改失败");
		}
		req.setAttribute("user", user);
		return Pages.USER_EDIT;
	}
	
	/**
	 * 前往用户管理界面
	 */
	@RequestMapping("/manager/user")
	public String toUserManager(HttpServletRequest req) {
		// 获取页码、页容量
		Integer pageNo = WebUtils.getInteger(req, "no", Pagination.DEFAULT_PAGE_NO);
		Integer pageSize = WebUtils.getInteger(req, "size", Pagination.DEFAULT_PAGE_SIZE);
		
		// 查询用户总数
		Integer totalCount = userService.countUsers();
		Pagination pagination = new Pagination(pageNo, pageSize, totalCount);
		pagination.setUrl("/manager/user");
		req.setAttribute("page", pagination);
		
		// 查询用户
		List<User> userList = userService.queryUserList(pagination.getStart(), pagination.getSize());
		req.setAttribute("userList", userList);
		return Pages.USER_MANAGER;
	}
	
	@RequestMapping("/manager/user/delete")
	public String deleteUser(HttpServletRequest req, HttpSession session) {
		Integer id = WebUtils.getInteger(req, "id", null);
		if (id == null) {
			return Pages.redirect("/manager/user");
		}
		// 判断是否是当前登录用户
		User loginUser = (User) session.getAttribute("loginUser");
		userService.deleteUser(id);
		if (loginUser.getId() == id) {
			session.removeAttribute("loginUser");
		}
		return Pages.redirect("/manager/user");
	}
}
